package com.prothink.threadadmindemo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.prothink.threadadmindemo.entity.UserEntity;
import com.prothink.threadadmindemo.exception.BisnessException;
import com.prothink.threadadmindemo.mapper.UserMapper;
import com.prothink.threadadmindemo.service.UserService;
import com.prothink.threadadmindemo.util.JWTTokenUtil;
import com.prothink.threadadmindemo.util.Md5Util;
import com.prothink.threadadmindemo.util.PwdUtil;
import com.prothink.threadadmindemo.vo.AccountVo;
import com.prothink.threadadmindemo.vo.ForgetPwdVo;
import com.prothink.threadadmindemo.vo.UserInfoVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.io.File;
import java.util.Date;
import java.util.List;

/**
 * @author mayanping
 * @title: UserServiceImpl
 * @projectName ThreadAdminDemo
 * @description: TODO
 * @date 2024/9/514:22
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private JavaMailSenderImpl mailSender;


    @Override
    public List<UserEntity> getUserList() {

        List<UserEntity> userList = userMapper.selectList(null);

        for(UserEntity user : userList){
            for(UserEntity user1 : userList){
                if(user.getCUser() == user1.getId()){
                    user.setCUserName(user1.getName());
                }

                if(user.getUUser() == user1.getId()){
                    user.setUUserName(user1.getName());
                }
            }
        }

        return userList;
    }

    @Override
    public void addUser(UserEntity user){
        userMapper.insert(user);
    }

    @Override
    public void registUser(AccountVo account){
        UserEntity userEntity = getUserByName(account.getAccount());
        if(userEntity != null){
            throw new BisnessException("该用户已注册:" + account.getAccount());
        }

        UserEntity user = new UserEntity();
        user.setAccount(account.getAccount());
        user.setPwd(Md5Util.md5Encript(account.getPwd()));
        user.setName(account.getAccount());
        user.setCTime(new Date());
        user.setUUser(0);
        user.setCUser(0);
        user.setUTime(new Date());
        userMapper.insert(user);
    }

    @Override
    public UserInfoVo login(AccountVo account){
        UserEntity userEntity = getUserByName(account.getAccount());
        if(userEntity == null){
            throw new BisnessException("该用户不存在:" + account.getAccount());
        }

        if(!userEntity.getPwd().equals(Md5Util.md5Encript(account.getPwd()))){
            throw new BisnessException("密码错误:" + account.getAccount());
        }

        String token = JWTTokenUtil.getToken(account.getAccount());

        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userEntity, userInfoVo);
        userInfoVo.setToken(token);

        return userInfoVo;
    }

    @Override
    public UserEntity getUserByName(String accountName){
        //select * from user where account = #{accountName}
        QueryWrapper<UserEntity> wrapper = new QueryWrapper();
        wrapper.eq("account", accountName);
        return userMapper.selectOne(wrapper);
    }

    /**
     * 重置密码：
     * 1. 查询用户的邮箱
     * 2. 生成一个随机的密码：数字+字母组合，长度为6
     * 3. 邮件发送
     * 4. 密码更新到数据库
     * @param forgetPwdVo
     */
    @Override
    public void resetPwd(ForgetPwdVo forgetPwdVo){
        /*
            1 查询用户的邮箱
            问题：
            Spring事务失效场景：
            1. 方法的内部调用
         */
        UserService userService = applicationContext.getBean(UserService.class);
        UserEntity user = userService.getUserByName(forgetPwdVo.getAccount());

        // 2 生成随机密码
        String password = PwdUtil.generatorPassword();

        // 邮件发送 Springboot 邮件发送
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        //邮件主题
        simpleMailMessage.setSubject("重置密码");
        //邮件正文
        simpleMailMessage.setText("您的新密码是： " + password);
        simpleMailMessage.setTo(user.getMail());
        simpleMailMessage.setFrom("yuddpky@163.com");

        mailSender.send(simpleMailMessage);


        //4 更新密码到数据库
        // update user set password = ${pwd}


        System.out.println(user);
    }

    @Override
    public void resetPwdWithAttachment(ForgetPwdVo forgetPwdVo) {
        /*
            1 查询用户的邮箱
            问题：
            Spring事务失效场景：
            1. 方法的内部调用
         */
        UserService userService = applicationContext.getBean(UserService.class);
        UserEntity user = userService.getUserByName(forgetPwdVo.getAccount());

        // 2 生成随机密码
        String password = PwdUtil.generatorPassword();

        //异步发送邮件
//        MyThreadPool.THREAD_POOL.submit(new SendMailTask(mailSender, user, password));

        this.sendMail(user, password);
    }

    @Async("myThreadPool")
    public void sendMail(UserEntity user, String password) {
        try {
            //创建复杂邮件的对象
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            //设置标题
            mimeMessageHelper.setSubject("重置密码");
            String htmlText = "<table><tr><th>账号：</th><th>密码：</th></tr><tr><td>%s</td><td>%s</td></tr></table>";
            htmlText = String.format(htmlText, user.getAccount(), password);
            mimeMessageHelper.setText(htmlText, true);

            //设置邮件附件 文件名称有中文可能会乱码
            File file = new File("/Users/mayanping/Desktop/进思/2309-C/2309-C周考-20240920/日测.zip");
            mimeMessageHelper.addAttachment("2309-C日测题-乱码", file);

            // 使用 encodeText、encodeWord 必须加上不截取配置
            System.getProperties().setProperty("mail.mime.splitlongparameters", "false");

            mimeMessageHelper.addAttachment(MimeUtility.encodeWord("2309-C日测题", "UTF-8", "B"), file);
            mimeMessageHelper.setTo(user.getMail());
            mimeMessageHelper.setFrom("yuddpky@163.com");

            mailSender.send(mimeMessage);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
